package com.bdy.lm.browser.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;

import com.bdy.lm.browser.domain.User;
import com.bdy.lm.browser.service.UserException;
import com.bdy.lm.browser.service.UserService;

@SuppressWarnings("serial")
public class UserServlet extends BaseServlet {

	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		UserService userService = new UserService();

		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		
//		Map<String, String[]> map = request.getParameterMap();
//		for(String name : map.keySet()){
//			String[] values = map.get(name);
//			System.out.println(values[0]);
//		}
//		User form = new User();
//		form.setIdentity(request.getParameter("identity"));
//		form.setName(request.getParameter("name"));
//		form.setPassword(request.getParameter("password"));

		try {//该部分能执行，则UserService中的三个判断均没有抛异常
			User user = userService.login(form);
			request.getSession().setAttribute("sessionUser", user);//正确，写入所查询的信息
			response.sendRedirect(request.getContextPath() + "/home/home.jsp");
		} catch (UserException e) {//若UserService有一个异常抛出，该部分执行
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("user", form);//错误，写入表单中的原始信息
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		}
	}
	
	public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserService userService = new UserService();
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		try {
			if (userService.register(form)) {
				request.setAttribute("user", form);
				response.sendRedirect(request.getContextPath() + "/home/home.jsp");
			} else {
				request.setAttribute("msg", "注册失败，请重新注册！");
				request.setAttribute("user", form);//错误，写入表单中的原始信息
				request.getRequestDispatcher("/user/register.jsp").forward(request, response);
			}
		} catch (UserException e) {//若UserService有一个异常抛出，该部分执行
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("user", form);//错误，写入表单中的原始信息
			request.getRequestDispatcher("/user/register.jsp").forward(request, response);
		}
	}
	
	public void exit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		User user = (User)request.getSession().getAttribute("sessionUser");
		if(user == null) {
			request.setAttribute("msg", "您还没有登录，不能退出！");
		} else {
			request.getSession().removeAttribute("sessionUser");
			//request.setAttribute("msg", "您已退出！");
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		}
		//System.out.print(user.toString());
	}

}
